package org.example.controller;

import org.example.entity.Menu;
import org.example.entity.MenuVO;
import org.example.entity.Type;
import org.example.feign.MenuFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/menu")
public class MenuHandler {

    @Autowired
    private MenuFeign menuFeign;

    @GetMapping("/findAll")
    @ResponseBody//只返数据不返视图
    public MenuVO findAll(@RequestParam("page") int page, @RequestParam("limit") int limit) {
        int index = (page-1)*limit;
        return menuFeign.findAll(index, limit);
    }

    @GetMapping("redirect/{location}")
    public ModelAndView redirect(@PathVariable("location") String location) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(location);

        return modelAndView;
    }

    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable("id") long id) {
        menuFeign.deleteById(id);
        return "redirect:/menu/redirect/menu_manage";
    }
    @GetMapping("/findTypes")
    public ModelAndView findTypes(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("menu_add");
    modelAndView.addObject("list", menuFeign.findTypes());
    return modelAndView;
    }

    @PostMapping("/save")
    public String save(Menu menu){
        menuFeign.save(menu);
        return "redirect:/menu/redirect/menu_manage";
    }

    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable("id") long id) {
        ModelAndView modelAndView = new ModelAndView();
        Menu menu = menuFeign.findById(id);
        List<Type> list = menuFeign.findTypes();
        modelAndView.setViewName("menu_update");
        modelAndView.addObject("menu", menu);
        modelAndView.addObject("list", list);
        return modelAndView;
    }

    @PostMapping("/update")
    public String update(Menu menu){
        menuFeign.update(menu);
        return "redirect:/menu/redirect/menu_manage";
    }

}
